package ice.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/*
 *   作者：icefield
 *   时间：2021/3/25
 *   描述：工具类
 */
public class tools {
    public static String value;

    public tools() {
    }

    /*
     *  作者：icefield
     *  说明：通过传入的jsonarray和值 获取对应的信息
     */
    public String getvalue(JSONArray ar,int type){

        ar.stream().forEach(jsonobejct-> {
            JSONObject jso = (JSONObject) jsonobejct;
//            System.out.println(jso.getIntValue("type"));
            if (jso.getIntValue("type")==type) {
                value = valuesBytype(jso.get("value"), type);
            }
        });

        return value;
    }

    /*
     *  作者：icefield
     *  说明：从jsonobject获取jsonarray信息 库得表处理
     */
    public String[] 从Jo获取(JSONObject js,String key){
        final String[] tables = new String[js.size()];
        if (!key.equals("")) {
            JSONArray ja = js.getJSONArray(key);
            if (ja==null) return null;
            tables[0] ="";
            final int[] i = {1};
            ja.stream().forEach(tbs->{
                String s = (String) tbs;
                tables[0] +=s+"    ";
                if(i[0] %8==0){
                    tables[0]+="\r\n";
                }
                i[0]++;
            });
        } else {
//            System.out.println("所有");
            Iterator<Map.Entry<String, Object>> iterator = js.entrySet().iterator();
            int i=0;
            while(iterator.hasNext()){
                tables[i]="";
                Map.Entry<String, Object> entry = iterator.next();
                tables[i]+=entry.getKey()+" ";
//                System.out.println("表    "+tables[i]);
                JSONArray ar = (JSONArray) entry.getValue();
                for (int j = 0; j < ar.size(); j++) {
                    tables[i]+=ar.get(j).toString()+" ";
                }
//                System.out.println(tables[i]);
                i++;
            }
        }
//        System.out.println(tables[0]);
        return tables;
    }
    private String valuesBytype(Object value,int type){
        String res="获取失败";
        switch (type){
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
                res = value.toString();
                break;
            case 8:

            default:
                res = value.toString();
        }
        System.out.println(value);
        return res;
    }

    /*
     *  作者：icefield
     *  说明：根据给定的表Jsonobject数据进行解析
     */
    public TableView 解析表值(JSONArray ar){
        Map<String, ArrayList<String>> map = new HashMap<>();
        String value = getvalue(ar, 17);
        JSONObject js = JSONObject.parseObject(value);
        ObservableList<表数据> 表数据s = FXCollections.observableArrayList();
        TableView tableView = new TableView();

        int 列数 = js.size()-1;
        int 行数 = js.getJSONObject("__infos__").getIntValue("count");
        if (列数<=20) {
            String[][] 数据 = new String[列数][行数];
            表数据[] ds=new 表数据[行数];
            String[] 列名=new String[列数];
            int j=0;
            Iterator<Map.Entry<String, Object>> iterator = js.entrySet().iterator();
            while(iterator.hasNext()){
                Map.Entry<String, Object> entry = iterator.next();
                String key=entry.getKey();
                JSONObject val = (JSONObject) entry.getValue();
    //            System.out.println("列："+val.toJSONString());
                if (!key.equals("__infos__")){
                    列名[j]=key;
                    JSONArray ja = val.getJSONArray("values");

                    for (int i = 0; i < ja.size(); i++) {
                        数据[j][i]=ja.getString(i);
                    }
                    j++;
                }
            }
            for (int i = 0; i < 行数; i++) {
                ArrayList<String> str = new ArrayList<>();
                for (int k = 0; k < 列数; k++) {
                    str.add(数据[k][i]);
                }
                ds[i]=new 表数据(str);
            }

//        System.out.println("表行数："+ds.length);


            for (表数据 b : ds) {
                表数据s.add(b);
            }
//        System.out.println("表数据s"+表数据s);


            TableColumn[] tableColumn=new TableColumn[列数];
            for (int i=0;i<列数;i++) {
                tableColumn[i] = new TableColumn(列名[i]);
                tableView.getColumns().add(tableColumn[i]);
                tableColumn[i].setCellValueFactory(new PropertyValueFactory<>("v"+i));
            }
        }else{
            表数据s.add(new 表数据("不支持超过20列的表"));
            TableColumn[] tableColumn=new TableColumn[1];
            TableColumn 错误 = new TableColumn("错误");
            错误.setCellValueFactory(new PropertyValueFactory<>("v0"));
            tableView.getColumns().add(错误);
        }

        tableView.setItems(表数据s);

        return tableView;
    }

    public static void 提醒弹窗(String msg){
        if (Platform.isFxApplicationThread()){
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(msg);
//            alert.initOwner(MainStage.mstage.l);
            alert.showAndWait();
        }else{
            Platform.runLater(()->{Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setContentText(msg);
                alert.showAndWait();});
        }
    }
    public void 展示表(TableView msg){
        if (Platform.isFxApplicationThread()){
            Stage stage = new Stage();
            AnchorPane anchorPane = new AnchorPane();
            anchorPane.getChildren().add(msg);
            anchorPane.setRightAnchor(msg,0.0);
            anchorPane.setLeftAnchor(msg,0.0);
            anchorPane.setTopAnchor(msg,0.0);
            anchorPane.setBottomAnchor(msg,0.0);
            stage.setScene(new Scene(anchorPane));
            stage.show();

        }else{
            Platform.runLater(()->{
                Stage stage = new Stage();
                AnchorPane anchorPane = new AnchorPane();
                anchorPane.getChildren().add(msg);
                anchorPane.setRightAnchor(msg,0.0);
                anchorPane.setLeftAnchor(msg,0.0);
                anchorPane.setTopAnchor(msg,0.0);
                anchorPane.setBottomAnchor(msg,0.0);

                stage.setScene(new Scene(anchorPane));
                stage.show();});
        }
    }

    public static void updataStatus(String msg, TextArea tx){
        if (Platform.isFxApplicationThread()){
            tx.appendText(msg+"\r\n");
        }else{
            Platform.runLater(()->{tx.appendText(msg);});
        }
    }



    public static void 写配置文件(File jsonFile, String str) throws IOException {

        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(jsonFile, false), "UTF-8");
        writer.write(str);
        writer.close();

    }

}
